package com.motu.monstercity.server.game.logic;

import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.patrol.PatrolLocation;
import com.motu.monstercity.server.game.commondata.patrol.PatrolTable;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.toolset.Tool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PatrolManager extends PatrolUserData {
    private static Logger logger = LoggerFactory.getLogger(PatrolManager.class);


    /**
     * 随机秘书事件
     * @return
     */
    public static PatrolTable randomPatrolTable(long userId) {
        List<UserSecretaryFragment> fragmentList = SecretaryManager.getUserSecretaryFragments(userId);
        Map<Integer, Integer> fragmentPercentMap = new HashMap<>();
        if (!fragmentList.isEmpty()) { // 如果存在碎片则过滤出好感度>=90%的秘书
            for (UserSecretaryFragment fragment : fragmentList) {
                PatrolTable patrolTable = getPatrolTableBySecretaryId(fragment.getSecretaryId());
                if (patrolTable == null || patrolTable.getFragmentNum() <= fragment.getNum()) { // 已完成的不再收集
                    continue;
                }
                int percent = fragment.getNum() * 100 / patrolTable.getFragmentNum();
                if (percent >= 90) {
                    fragmentPercentMap.put(fragment.getSecretaryId(), percent);
                }
            }
        }
        List<PatrolTable> tableList = new ArrayList<>();
        // 如果有好感度>=90%的，就取出好感度最大的
        if (!fragmentPercentMap.isEmpty()) {
            int maxPercent = fragmentPercentMap.entrySet().stream().max(Map.Entry.comparingByValue()).get().getValue();
            List<Integer> maxSecretaryList = fragmentPercentMap.entrySet().stream().filter(e -> e.getValue() == maxPercent).map(Map.Entry::getKey).toList();
            if (maxSecretaryList.size() == 1) { // 如果只有一个好感度最大的，就直接返回这个秘书
                int secretaryId = maxSecretaryList.get(0);
                return getPatrolTableBySecretaryId(secretaryId);
            }
            // 如果有两个以上是同样好感度的，就全取出来按权重随机
            for (Integer secretaryId : maxSecretaryList) {
                PatrolTable patrolTable = getPatrolTableBySecretaryId(secretaryId);
                if (null != patrolTable) {
                    tableList.add(patrolTable);
                }
            }
        }
        if (tableList.isEmpty()) { // 如果没有好感度>=90%的秘书就全部随机
            tableList.addAll(getPatrolTableMap().values());
        }
        int weight = 0;
        for (PatrolTable patrolTable : tableList) {
            weight += patrolTable.getSecretaryWeight();
        }
        int randomWeight = Tool.getRandom(0, weight);
        weight = 0;
        PatrolTable table = null;
        for (PatrolTable patrolTable : tableList) {
            table = patrolTable;
            weight += patrolTable.getSecretaryWeight();
            if (weight >= randomWeight) {
                break;
            }
        }
        return table;
    }

    /**
     * 增加秘书的好感度或亲密度
     * @param userInfo
     * @param location
     * @param patrolTable
     * @param pbUserData
     */
    public static void addSecretaryPatrol(UserInfo userInfo, UserPower userPower, UserAffair userAffair, PatrolLocation location, PatrolTable patrolTable, PBUserData.Builder pbUserData) {
        long userId = userInfo.getId();
        int[] secretaryRewardArray = location.getSecretaryRewardArray();
        if (secretaryRewardArray.length > 1) {
            int secretaryId = secretaryRewardArray[0];
            int rewardNum = secretaryRewardArray[1];
            UserSecretary secretary = SecretaryManager.getUserSecretary(userId, secretaryId);
            if (secretary == null) { // 如果是未获得的秘书就增加好感度
                UserSecretaryFragment userSecretaryFragment = SecretaryManager.getUserSecretaryFragment(userId, secretaryId);
                if (userSecretaryFragment == null) {
                    userSecretaryFragment = new UserSecretaryFragment(userId, secretaryId);
                    userSecretaryFragment.putNum(rewardNum);
                    userSecretaryFragment.doCreate();
                } else {
                    userSecretaryFragment.addNum(rewardNum);
                    userSecretaryFragment.update();
                }
                ProtoDataUtils.updatePBUserData(pbUserData, userSecretaryFragment);
//                logger.info("### addSecretaryPatrol userId={}, secretaryId={}, fragNum={} ", userId, secretaryId, patrolTable.getFragmentNum());
                if (userSecretaryFragment.getNum() >= patrolTable.getFragmentNum()) { // 如果好感度达到最大值则获得秘书
//                    logger.info("### addSecretaryPatrol translate userId={}, secretaryId={} ", userId, secretaryId);
                    RewardManager.addReward(userInfo, secretaryId, 1, pbUserData, LogType.PATROL_BEGIN);
                    MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_161, rewardNum);
                    RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_161, rewardNum);
                }
            } else {
                secretary.addFavorite(pbUserData, userInfo, userPower, userAffair, rewardNum);
                secretary.update();
                ProtoDataUtils.updatePBUserData(pbUserData, secretary);
            }

            MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_180, 1, secretaryId);
            RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_180, 1, secretaryId);
        }
    }


}
